<template>
  <view class="container">
    <outline :cashList="formData" v-if="formData.length"></outline>
    <uni-popup ref="popup" type="center" :is-mask-click="true" borderRadius="10px 10px 10px 10px"
      mask-background-color="rgba(233, 233, 233, 0.4)" background-color="white">
      <view class="popUp">
        <view class="top-box">
          <view class="title" style="text-align: center;">
            选择头像
          </view>
          <uni-icons @click="popupClose" type="closeempty" size="30"
            style="text-align: rigth;padding: 15px;"></uni-icons>
        </view>
        <scroll-view scroll-y class="img-scroll">
          <view class="imgList">
            <view class="" style="position: relative;" v-for="(item,index) in avtarList" :key="index + 'olo'">
              <image class="img" mode="aspectFit" @click="seletAvtar(item.imageUrl)" :src="item.imageUrl">
              </image>
              <uni-icons type="trash" style="position: absolute;bottom: 14px;right: 6px;" size="24"
                @click="deleAvtar(index,item._id)"></uni-icons>
            </view>
          </view>
          <view class="av-content">
            <uni-file-picker ref="filePicker" disable-preview :del-icon="false" return-type="object"
              file-mediatype="image" :image-styles="imageStyles" @success="uploadSuccess" @fail="uploadFail">
            </uni-file-picker>
            <!--  -->
          </view>
        </scroll-view>
      </view>
    </uni-popup>
    <!-- 数据渲染表 -->
    <view class="">
      <uni-forms class="form-container" v-for="(data,index) in formData" :key="index + '1l'">
        <uni-forms-item name="content" :label="'题目' + (index+1)" required>
          <view class="" style="display: flex;align-items: center;">
            <uni-easyinput placeholder="标题" style="width: 550px" v-model="data.title" :maxlength="-1" autoHeight
              type="textarea" trim="both"></uni-easyinput>
            <uni-icons style="margin-left: 30px;" type="trash-filled" size="32" @click="deleTitle(index)"></uni-icons>
          </view>
        </uni-forms-item>
        <uni-forms-item name="content" label="对话">
          <!-- 对话内容 -->
          <view class="coversation-box" v-for="(chat,chatIndex) in data.coversine" :key="chatIndex + 'chat'">
            <image style="width: 80px;height: 80px;border-radius: 100%;border: 1px dotted #007aff;" mode="aspectFit"
              @click="popupOpen(index,chatIndex)"
              :src="chat.avtarImg?chat.avtarImg:'https://tse1-mm.cn.bing.net/th/id/OIP-C.yFCZ8aCJfBCwxD5zKPka7QHaHa?rs=1&pid=ImgDetMain'">
            </image>
            <uni-easyinput placeholder="输入内容" style="width: 520px;padding: 20px" :maxlength="-1" v-model="chat.content"
              autoHeight type="textarea" trim="both"></uni-easyinput>
            <view class="uni-px-5 uni-pb-5">
              <uni-data-checkbox v-model="chat.mode" :key="chatIndex+'check'" :localdata="checkList"
                @change="radioChange($event,index,chatIndex)"></uni-data-checkbox>
            </view>
            <uni-icons type="trash-filled" size="26" @click="deleCoversine(index,chatIndex)"></uni-icons>
          </view>
          <button type="primary" class="uni-button" style="width: 130px; margin-left: 70px"
            @click="addCoversine(index)">添加对话</button>
        </uni-forms-item>
        <view class="options" v-for="(item, index2) in data.options" :key="index2">
          <uni-forms-item :name="index2 + 'l'" :label="'选项' + (index2 + 1)" required>
            <uni-easyinput placeholder="输入内容" style="width: 550px" :maxlength="-1" v-model="item.select" autoHeight
              type="textarea" trim="both"></uni-easyinput>
          </uni-forms-item>
          <view class="score">
            <uni-forms-item :name="index2 + 'S'" label="分数" required>
              <uni-easyinput placeholder="输入内容" style="width: 100px" v-model="item.score" autoHeight
                type="number"></uni-easyinput>
            </uni-forms-item>
          </view>
          <!-- <button type="primary" class="uni-button" style="width: 70px; margin: 0 12px"
					@click="addNextOption(item)">关联</button> -->
          <view class="score">
            <uni-forms-item :name="index2 + 'T'" label="跳转" required>
              <uni-easyinput placeholder="输入内容" style="width: 100px" v-model="item.nextOrder" autoHeight
                type="number"></uni-easyinput>
            </uni-forms-item>
          </view>
          <uni-icons type="trash-filled" size="32" @click="deleSect(index,index2)"></uni-icons>
        </view>
        <button type="primary" class="uni-button" style="width: 130px; margin-left: 70px"
          @click="addSelect(index)">增加选项</button>
        <view class="" style="border-bottom:1px solid #007aff;margin: 20px 0;"></view>
      </uni-forms>

      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 130px; margin-left: 70px"
          @click="addQuestion">新增题目</button>
      </view>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px" @click="submit">保存</button>
        <navigator open-type="navigateBack" style="margin-left: 15px">
          <button class="uni-button" style="width: 100px">返回</button>
        </navigator>
      </view>
    </view>
    <!-- 数据渲染表 -->

  </view>
</template>

<script>
  import outline from '../../components/outline/outline.vue';
  export default {
    components: {
      outline
    },
    data() {
      return {
        chatIndex: null, //聊天句子的下表
        index: null, //操作题数的下标
        avtarImage: {}, //上传图片后的对象
        left: 'left',
        checkList: [{
          "value": "left",
          "text": "居左"
        }, {
          "value": "center",
          "text": "局中"
        }, {
          "value": "right",
          "text": "居右"
        }],
        avtarList: [],
        imageStyles: {
          width: 130,
          height: 130,
          border: {
            color: "#7a7a7a",
            width: 2,
            style: 'dashed',
            radius: '2px'
          }
        },
        titleList: [],
        formData: [{
          title: '',
          coversine: [],
          options: [{
            select: '',
            score: 0,
            nextOrder: null
          }]
        }], //初始化值
        sampleObj: {
          title: '',
          coversine: [],
          options: [{
            select: '',
            score: 0,
            nextOrder: null
          }]
        }, //标准数据	
        cashID: '',
      };
    },
    // watch: {
    //   formData: {
    //     handler(val) {
    //       console.log("formData", val);
    //     },
    //     deep: true
    //   },
    onLoad(opt) {
      this.cashID = opt.id;
      this.init();
    },
    methods: {
      init() {
        // 拉取该id下的案例题目， 将案例的第一个题目赋值给formdata
        uniCloud
          .callFunction({
            name: 'admin-getCashRead',
            data: {
              _id: this.cashID,
              flag: 1
            }
          })
          .then((res) => {
            console.log(res.result.data)
            if (res?.result?.data[0]?.data.length > 0) this.formData = res.result.data[0].data
            else this.formData = [JSON.parse(JSON.stringify(this.sampleObj))]
          });
        uniCloud.callFunction({
          name: "getImageList",
          data: {
            flag: 1
          }
        }).then(res => {
          this.avtarList = res.result.data
        })
      },
      addSelect(index) {
        // console.log(index)
        //增加选项	
        this.formData[index].options.push({
          score: 0,
          nextOrder: null,
          select: ''
        });
        this.$forceUpdate();
      },
      deleCoversine(index, index2) {
        uni.showModal({
          title: '删除提示',
          content: '是否删除该句子',
          confirmText: '确认',
          success: res => {
            if (res.confirm) {
              this.formData[index].coversine.splice(index2, 1);
            }
          }
        })
      },
      deleAvtar(index, id) {
        uni.showModal({
          title: '删除提示',
          content: '是否删除该图片',
          confirmText: '确认',
          success: res => {
            if (res.confirm) {
              uniCloud.callFunction({
                name: "getImageList",
                data: {
                  id,
                  flag: 3
                }
              }).then(res => {
                // console.log(res)
                this.avtarList.splice(index, 1)
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });

              })
            }
          }
        })
      },
      deleTitle(index) {
        uni.showModal({
          title: '删除提示',
          content: '是否删除该题目',
          confirmText: '确认',
          success: res => {
            if (res.confirm) {
              this.formData.splice(index, 1)
            }
          }
        })
        //删除title
      },
      deleSect(index, index2) {
        uni.showModal({
          title: '删除提示',
          content: '是否删除该选项',
          confirmText: '确认',
          success: res => {
            if (res.confirm) {
              this.formData[index].options.splice(index2, 1);
            }
          },
        })
        //delet选项	
      },
      addCoversine(index) {
        this.formData[index].coversine.push({
          mode: "left",
          avtarImg: null,
          content: ''
        })
      },
      seletAvtar(imageUrl) {
        this.formData[this.index].coversine[this.chatIndex].avtarImg = imageUrl
        this.$refs.popup.close()
        this.index = this.chatIndex = null
      },
      radioChange(e, index, chatIndex) {
        // this.formData[index].coversine[chatIndex].mode = e.detail.data.value
        console.log(e.detail.data.value, index, chatIndex);
      },
      popupOpen(index, chatIndex) {
        //打开选择头像弹出层
        this.index = index
        this.chatIndex = chatIndex
        this.$refs.popup.open()
      },
      popupClose() {
        //关闭选择头像弹出层
        this.$refs.popup.close()
      },
      addQuestion() {
        // console.log("增加题目", this.formData)
        this.formData.push(JSON.parse(JSON.stringify(this.sampleObj)))
        this.$forceUpdate();

      },
      uploadFail(e) {
        uni.showToast({
          icon: 'fail',
          title: "上传失败"
        })
        console.log("上传失败", e)
      },
      uploadSuccess(e) {
        console.log("上传成功", e)
        this.avtarList.push({
          imageUrl: e.tempFiles[0].url
        })
        //上传到数据库
        uniCloud.callFunction({
          name: "getImageList",
          data: {
            flag: 2,
            imagePath: e.tempFiles[0].url
          }
        }).then(res => {
          // console.log(res)
          this.$refs.filePicker.clearFiles()
          //add ,返回ID
          uni.showToast({
            icon: 'fail',
            title: "上传成功"
          })
        })
      },
      submit() {
        return new Promise(async (resolve) => {
          // console.log("sub", this.checkOption());
          if (this.checkOption()) {
            let title = this.checkOption();
            uni.showToast({
              title,
              icon: 'error'
            });
            return;
          }
          // return console.log("no problom", this.formData)
          uni.showLoading({
            mask: true,
            title: '保存中...'
          });
          let res = await uniCloud.callFunction({
            name: 'admin-getCashRead',
            data: {
              _id: this.cashID,
              data: this.formData,
              flag: 2
            }
          });
          // console.log(res);
          if (res.result.updated == 1 || res.result.id) {
            console.log('上传/更新成功');
            uni.showToast({
              title: '保存成功'
            });
          }
          // setTimeout(() => uni.navigateBack(), 500)
          // this.updataOutline();
          uni.hideLoading();
          resolve();
        });
      },
      async addNextOption(obj) {
        /* 保存本题*/
        await this.submit();
        // 更新大纲
        if (obj.question) {
          this.formData = obj.question;
        } else {
          console.log('无 添加一个');
          obj.question = JSON.parse(JSON.stringify(this.sampleObj));
          this.formData = obj.question;
          this.$forceUpdate();
        }
        // console.log(this.formData, obj);
      },
      getTitle(param) {
        param.forEach((item) => {
          if (item.question && item.question.title) {
            this.titleList.push(item.question.title);
            if (item.question.options.length) this.getTitle(item.question.options);
          }
        });
      },
      checkOption() {
        /* 检查是否有问题*/
        try {
          this.formData.forEach((item, index) => {
            if (!item.title) throw `第${index + 1}题目不能为空`;
            item.options.forEach((item2, index2) => {
              if (!item2.nextOrder) throw `第${index + 1}题的第${index2 + 1}选项跳转题号不能为空`;
              if (!item2.select) throw `第${index + 1}题的第${index2 + 1}选项不能为空`;
            })
          })
        } catch (e) {
          return e
        }

      }
    }
  };
</script>

<style lang="scss">
  .container {
    display: flex;
    min-height: 850px;


    .coversation-box {
      display: flex;
      align-items: center;
    }

    .popUp {
      width: 900px;
      min-height: 500px;
      padding-bottom: 20px;
      padding-right: 20px;

      // border: 1px solid red;
      // display: flex;
      // align-items: center;
      // justify-content: center;
      .img-scroll {
        width: 100%;
        margin-left: 18px;
        height: 500px;
      }

      .imgList {
        display: grid;
        flex-wrap: wrap;
        grid-template-columns: repeat(7, 1fr);
        width: 100%;
        // margin-left: 18px;
        // height: 500px;

        .img {
          height: 100px;
          width: 100px;
          border-radius: 100%;
          border: 1px dotted black;
          margin: 10px;
        }

        .av-content {
          padding: 10px 20px;
        }
      }

      .top-box {
        width: 100%;
        display: flex;

        .title {
          width: 100%;
          padding: 20px;
          font-weight: 700;
          font-size: 20px;
        }
      }

    }

    .form-container {
      padding: 15px;
      max-width: 900px;
      display: block;


      .options {
        display: flex;
        align-items: center;
      }

      .score {
        margin: 0 20px;

        ::v-deep .uni-forms-item {
          flex-direction: column !important;
          align-items: center !important;

          .uni-forms-item__label {
            justify-content: center !important;
          }
        }
      }
    }
  }
</style>